package com.tx.admin.modules.base.runner;

import com.tx.admin.core.constant.SuperConstant.SuperEnum;
import com.tx.admin.modules.base.entity.DictionariesEntity;
import com.tx.admin.modules.base.service.DictionariesService;
import com.tx.admin.util.common.ClassUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import java.io.File;
import java.util.LinkedList;

@Component
public class CommonRunner implements CommandLineRunner {

    @Autowired
    private DictionariesService dictionariesService;

    private void initDictionaries()throws Exception{
        LinkedList list = new LinkedList<>();

        for (File modules : ClassUtil.getModules()) {
            File constantModules =  new File(modules.getPath()+"/constant");
            DictionariesEntity grandpa=  new DictionariesEntity();
            grandpa.setId(modules.getName());
            grandpa.setLabel(modules.getName());
            grandpa.setValue(modules.getName());
            grandpa.init();
            list.add(grandpa);
            if(constantModules.isDirectory()) {
                for (File constantFile : constantModules.listFiles()) {
                    Class clazz = ClassUtil.fileToClass(constantFile);
                    if(clazz.isEnum() && SuperEnum.class.isAssignableFrom(clazz)){
                        DictionariesEntity parent=  new DictionariesEntity();
                        parent.setId(clazz.getName());
                        parent.setLabel(clazz.getName());
                        parent.setValue(clazz.getName());
                        parent.setParentId(grandpa.getId());
                        parent.init();
                        list.add(parent);
                        if(clazz.getEnumConstants() == null){
                            continue;
                        }
                        SuperEnum[] es = (SuperEnum[])clazz.getEnumConstants();
                        for (SuperEnum e : es) {
                            DictionariesEntity children=  new DictionariesEntity();
                            children.setParentId(parent.getId());
                            children.setId(clazz.getName()+e.getLabel());
                            children.setLabel(e.getLabel());
                            children.setValue(e.getValue());
                            children.init();
                            list.add(children);
                        }
                    }
                }
            }


        }

        this.dictionariesService.save(list);

    }


    @Override
    public void run(String... args) throws Exception {
       if(dictionariesService.count() == 0){
          this.initDictionaries();
       }
    }
}

